/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.asu.cse360.service.impl;

import edu.asu.cse360.dto.ImageDto;
import edu.asu.cse360.service.PhotoService;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;

@Service("photoService")
public class PhotoServiceImpl implements PhotoService, ServletContextAware{

    private ServletContext servletContext;
    private static final String CONTEXT_PATH = "http://smashingmashups.com/cse360-server-0.0.1-SNAPSHOT/";

    @Override
    public ImageDto save(ImageDto imageDto) {
        try {
            String relativePath = "photo"+Math.random()+".jpg";
            String path = servletContext.getRealPath("/");
            File file = new File(path+relativePath);
            ImageIO.write(imageDto.getImage(),"jpg", file);
            String absolutePath = CONTEXT_PATH + relativePath;
            return new ImageDto(absolutePath, imageDto.getImage());
        } catch (IOException ex) {
            //Logger.getLogger(PhotoServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}
